package com.zhiyou.work;

import java.util.ArrayList;
import java.util.Iterator;

//貨物管理
public class Manager {

	ArrayList<Goods> list = new ArrayList<>();
	
	//新增
	public  void add(Goods newGoods){
		//变量 标示集合里有没有该货物
		boolean isExist = false;
		for (int i = 0; i < list.size(); i++) {
			Goods goods = list.get(i);
			if (goods.getNumber() == newGoods.getNumber()) {
				//有该货物  增加库存
				goods.setStock( goods.getStock() + newGoods.getStock()   );
				isExist = true;
				break;
			}
		}
		//isExist   isExist == true
		//!isExist  isExist == false
		if(!isExist){
			//新增
			list.add(newGoods);
		}
	}
	
	//查看
	public  void  check(){
		for (Goods goods : list) {
			System.out.println(goods);
		}
	}
	
	//修改    修改价格   
	public void modify(int number,float price){
		
		for (int i = 0; i < list.size(); i++) {
			Goods goods = list.get(i);
			if (goods.getNumber() == number) {
				//修改价格
				goods.setPrice(price);
			}
		}
		
	}
	
	//下架     
	public void delete(int number){
		//foreach 遍历集合时，一般不要 边遍历边删除元素
		/*
		for (Goods goods : list) {
			if (goods.getNumber() == number) {
				list.remove(goods);
				//break 跳出for循环
				//return 结束方法
				return;
			}
		}
		*/
		//迭代器
				/*
				Iterator<Goods> iterator =  list.iterator();
				while(iterator.hasNext()){
					Goods goods = iterator.next();
					if (goods.getStock() == number) {
						list.remove(goods);
						break;
					}
				}
				*/
		
		//普通for循环，删除多个元素时，元素会错乱
		/*
		for (int i = 0; i < list.size(); i++) {
			Goods goods = list.get(i);
			if (goods.getStock() == number) {
				list.remove(i);
			}
		}
		*/
		
		
		
		//飞机   坦克   火箭
		//0    1     2
		
		
		//倒序遍历
		for(int i=list.size()-1;i>=0;i--){
			Goods goods = list.get(i);
			if (goods.getStock() == number) {
				list.remove(i);
			}
		}
	}
	
	
	
}
